import component from "../../../component/Component.js"
import SensorUtils from "../SensorUtils.js";
import { LayerType, ServiceType } from "../../../experience/db/Type.js"
import Type from "../../../experience/db/Type.js";

const Draw = ol.interaction.Draw;
const Style = ol.style.Style;
const Fill = ol.style.Fill;
const Stroke = ol.style.Stroke;
const CircleStyle = ol.style.Circle;

export default class VentilationArrowRender extends component {
    constructor() { super() }

    async control() {
        this.ztreeUtil = new SensorUtils();
        this.currentLineFeature = null;
        this.currentReadyDeleteVId = '';
        this.currentVentilateType = '';
        this.animationTimer = null;
        this.runningSwitch = false;
        this.$$('#windDirection').on('click', () => this.ventilayeArrowSet());

        // 创建 选择进风或者回风的弹窗
        this.VentilateTypeDialog = this.app.dialog.create({
            title:'风向类型选择',
            text:'请选择风向类型',
            buttons:[
                {
                    text:'进风',
                    onClick:() => {
                        console.log('进风');
                        this.currentVentilateType = '进风';
                        this.submitVentilateInfo();
                    }
                },
                {
                    text:'回风',
                    onClick:() => {
                        console.log('回风');
                        this.currentVentilateType = '回风';
                        this.submitVentilateInfo();
                    }
                }
            ]
        })

        this.emitter.on('ventilate-animation',() => {
            const ventilateLayer = this.drawer.drawer.SMVentilate
            if(!this.animationTimer) {
                this.animationTimer = setInterval(() => {
                    if(this.runningSwitch) {
                        ventilateLayer.setVisible(!ventilateLayer.getVisible());
                    } else {
                        ventilateLayer.setVisible(false);
                    }
                },2100);
            }
        });

        this.emitter.on('delete-ventilate', () => {
            this.currentReadyDeleteVId = this.emitter.params[0];
            this.app.dialog.confirm('是否删除该风向线','风向系统',this.deleteVentilate.bind(this));
        })
        // 开启 通风系统 展示开关的事件
        this.emitter.on('open-ventilate', () => {
            this.runningSwitch = true;
        })

        // 关闭 通风系统 展示开关的事件
        this.emitter.on('close-ventilate', () => {
            this.runningSwitch = false;
        })

    }

    template() {
        const windDirectionRenderBtn = `
            <div id="windDirection" class="GisUtilIcon" 
                style="position: absolute; top: 200px; left: 25px; z-index: 999">
                <i class="fas fa-wind"></i>
            </div>
        `;
        this.$$("body").append(windDirectionRenderBtn);
        const editStatus = this.utils.getUrlParamer('edit');
        if(editStatus === 'true') {
            this.$$('#windDirection').show();
        } else {
            this.$$('#windDirection').hide();
        }
    }
    async deleteVentilate() {
        const ventilateId = this.currentReadyDeleteVId;
        const { data } = await this.api.deleteSmVentilate(
            ServiceType.Mine_Id, 'person', ventilateId
        );
        // 删除结束之后 ，先将本地数据库与远端进行同步
        // 同时 把图纸的版本也进行同步，避免本机 重复同步数据
        const meta = data.meta;
        await this.db.refreshMeta(meta);
        await this.db.refresh(LayerType.SMVentilate, data.data);
        // 重新渲染风向线
        await this.drawer._safeMonitorVentilate();
    }

    // 设置风向的函数
    ventilayeArrowSet() {
        const modifySource = this.drawer.source(Type.Modify);
        // 创建画的 gis交互
        const drawInteraction = new Draw({
            source: modifySource,
            type: 'LineString',
            maxPoints:2,
            style: new Style({
                fill: new Fill({
                    color: 'rgba(255, 255, 255, 0.2)',
                }),
                stroke: new Stroke({
                    color: 'orange',
                    lineDash: [10, 10],
                    width: 2,
                }),
                image: new CircleStyle({
                    radius: 3,
                    stroke: new Stroke({
                        color: 'rgba(255, 0, 0, 0.7)',
                    }),
                    fill: new Fill({
                        color: 'rgba(255, 255, 255, 1)',
                    }),
                }),
            }),
        });

        this.drawInteraction = drawInteraction
        drawInteraction.on('drawend',async (event) => {
            this.VentilateTypeDialog.open();
            this.currentLineFeature = event.feature;
        });
        this.drawer.map.addInteraction(drawInteraction);
        this.runningSwitch = false;
    }

    async submitVentilateInfo() {
        const modifySource = this.drawer.source(Type.Modify);
        const feature = this.currentLineFeature;
        const ventilateType = this.currentVentilateType;
        const  drawInteraction = this.drawInteraction;
        const point = feature.getGeometry().getCoordinates();
        const sp = [this.algo.denormalX(point[0][0]), this.algo.denormalY(point[0][1])];
        const ep =  [this.algo.denormalX(point[1][0]), this.algo.denormalY(point[1][1])];
        this.drawer.map.removeInteraction(drawInteraction)
        const timer = setTimeout(() => {
            modifySource.clear();
            clearTimeout(timer);
        },300);
        const slope = (ep[1] - sp[1]) / (ep[0] - sp[0]);
        const rotation = -this.ztreeUtil.get_rel_rotation(ep, sp, slope);
        const ventilateId = this.ztreeUtil.uuid();
        const { data } = await this.api.addSmVentilate(
            ServiceType.Mine_Id,
            'person',
            ventilateId,
            rotation,
            sp[0],
            sp[1],
            ep[0],
            ep[1],
            ventilateType
        );
        //先将本地数据库与远端进行同步
        await this.db.refresh(LayerType.SMVentilate, data.data);
        // 同时 把图纸的版本也进行同步，避免本机 重复同步数据
        await this.db.refreshMeta(data.meta);
        // 重新渲染风向线
        await this.drawer._safeMonitorVentilate();
        this.drawer.drawer.SMVentilate.setVisible(true);
        this.runningSwitch = true;
    }
}

